package ext.tianma.project;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.ReferenceFactory;
import wt.folder.Folder;
import wt.httpgw.URLFactory;
import wt.org.WTPrincipal;
import wt.org.WTUser;
import wt.pom.Transaction;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.Iterated;
import wt.vc.wip.CheckoutLink;
import wt.vc.wip.WorkInProgressHelper;
import wt.vc.wip.Workable;

import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.forms.FormResultAction;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.util.beans.NmCommandBean;
import com.ptc.netmarkets.util.misc.NmActionServiceHelper;

import ext.tianma.soap.CrmResponse;
import ext.tianma.soap.SOAPService;

public class UpdateProjectProcessor {
	public static void main(String[] args){
		String ESDate = "";
		SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy/MM/dd");
		try {
			String s = df.format(format.parse(ESDate));
			System.out.println(s);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * ��ȡ�����PLM��ֵ
	 * @param v
	 * @return
	 */
	private static String getPLMValue(String v){
		if(v.indexOf(":")>=0){
			return v.split(":")[0];
		}else{
			return "";
		}
	}
	/**
	 * ��ȡ�����CRM��ֵ
	 * @param v
	 * @return
	 */
	private static String getCRMValue(String v){
		if(v.indexOf(":")>=0){
			return v.split(":")[1];
		}else{
			return "";
		}
	}
	/**
	 * ����û���д����ݣ�����Project��������
	 * @param commandBean
	 * @return
	 * @throws WTException
	 */
	 public static FormResult updateProject(NmCommandBean commandBean) throws WTException {
	        FormResult formResult = new FormResult();
	        Persistable pbo = null;
	        Transaction trans = new Transaction();
	        WTPrincipal currentuser =SessionHelper.manager.getPrincipal();
	        try {
	        	SessionServerHelper.manager.setAccessEnforced(false); 
	            trans.start();
	            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
	            String ESDate = commandBean.getTextParameter("ESDate");
	            String CSDate = commandBean.getTextParameter("CSDate");
	            String MPDate = commandBean.getTextParameter("MPDate");
	            String issue = commandBean.getTextParameter("issue");
	            String impact = commandBean.getTextParameter("impact");
	            String status = commandBean.getTextParameter("status");
	            String phase = commandBean.getTextParameter("phase");
	            Object actionObj = commandBean.getActionOid().getRefObject();
	            pbo = (Persistable) actionObj;
	            String guid = (String)LWCUtil.getValue(pbo, "GUID");
//	            pbo = checkout(pbo,"");
	            Map ibamap = new HashMap();
//	            ibamap.put("testString", ESDate+"-"+status);
	            if(ESDate != null && !"".equals(ESDate)){
	            	ibamap.put("DR1ReviewActualTime", Timestamp.valueOf(df.format(format.parse(ESDate)) ));
	            }
	            ibamap.put("ProjectIssue", issue);
	            ibamap.put("ProjectStatus", getPLMValue(status));
	            ibamap.put("PlantProjectPases", getPLMValue(phase));
	            ibamap.put("MainProblem", impact);
	            if(CSDate != null && !"".equals(CSDate)){
	            	ibamap.put("ESPhaseReviewCSActualTime", Timestamp.valueOf(df.format(format.parse(CSDate)) ));
	            }
	            if(MPDate != null && !"".equals(MPDate)){
	            	ibamap.put("DR3CSPhaseReviewActualTime", Timestamp.valueOf(df.format(format.parse(MPDate)) ));
	            }
	            LWCUtil.setValue(pbo, ibamap);
	            
	            trans.commit();
//	            pbo = checkin(pbo,"Update Project Info.");
	            //PlantProjectPases -- phase
	            //DR1ReviewActualTime -- ESDate
	            //ESPhaseReviewCSActualTime -- CSDate
	            //DR3CSPhaseReviewActualTime -- MPDate
	            // ProjectStatus -- status
	            //ProjectIssue -- issue
	            //MainProblem -- impact
	            //GUID -- GUID
				String xmlData = SOAPService.getProjectXmlData(guid, getCRMValue(status),getCRMValue(phase), ESDate, CSDate, MPDate, impact, issue);
//				System.out.println("-----------------"+xmlData);
				CrmResponse crmRes = SOAPService.sendProject(xmlData);
				if (crmRes == null) {
//					System.out.println("parse error.");
					throw new Exception("Parse resonse error.");
				} else {
					//System.out.println(crmRes);
					if("0".equals(crmRes.getCode())){
						throw new Exception("����CRMϵͳʧ��,����ϵϵͳ����Ա��������Ϣ��"+crmRes.getMsg());
					}
				}
				FeedbackMessage returnMsg = new FeedbackMessage(FeedbackType.SUCCESS, SessionHelper.getLocale(), null,
	                    null, "更新成功["+crmRes.getCode()+"]!");
	            formResult.addFeedbackMessage(returnMsg);
	            formResult.setURL(genInfoPageURL(pbo));
	            formResult.setNextAction(FormResultAction.LOAD_OPENER_URL);
	            
	        } catch (Exception e) {
	        	e.printStackTrace();
	            FormResult resultFailure = new FormResult();
	            resultFailure.setNextAction(FormResultAction.NONE);
	            resultFailure.setStatus(FormProcessingStatus.FAILURE);
	            resultFailure.addException(e);
	            trans.rollback();
	            return resultFailure;
	        } finally {
	            SessionServerHelper.manager.setAccessEnforced(true); 
	            if (trans != null) {
	                trans = null;
	            }
	        }
	        return formResult;
	    }
	 /**
	  * ��õ�ǰproject��URL
	  * @param persistable
	  * @return
	  * @throws WTException
	  */
	    public static String genInfoPageURL(Persistable persistable) throws WTException{
	    	ReferenceFactory referencefactory = new ReferenceFactory();
	    	String oid = referencefactory.getReferenceString(persistable);
	    	return "ptc1/project/details?oid="+oid+"&u8=1";
	    	/*
	    	URLFactory urlfactory = new URLFactory();
	    	HashMap map = new HashMap();
	    	map.put("oid", oid);
			String action =  NmActionServiceHelper.service.getAction("object", "view").getUrl();
	        return urlfactory.getHREF(action, map, true);
	        */
	    }
	    
	    public static Workable checkout(Workable w, String note)
	            throws WTPropertyVetoException, WTException {
	        if (w instanceof Iterated) {
	            Iterated it = (Iterated) w;
	            w = (Workable) wt.vc.VersionControlHelper.service
	                    .getLatestIteration(it, false);
	        }
	        Workable wk = null;
	        boolean checkoutFlag = WorkInProgressHelper.isCheckedOut(w);
	        if (checkoutFlag) {
	            if (!WorkInProgressHelper.isWorkingCopy(w))
	                wk = WorkInProgressHelper.service.workingCopyOf(w);
	            else
	                wk = w;
	        } else {
	            Folder myFolder = WorkInProgressHelper.service.getCheckoutFolder();
	            CheckoutLink checkout_lnk = WorkInProgressHelper.service.checkout(
	                    w, myFolder, note);
	            wk = checkout_lnk.getWorkingCopy();
	        }
	        return wk;
	    }
	    
	    public static Workable checkin(Workable w, String note)
	            throws WTPropertyVetoException, WTException {
	        WTUser user = (WTUser) wt.session.SessionHelper.manager.getPrincipal();
	        note = note + "," + (new Date()).toString() + "," + user.getName()
	                + "/" + user.getFullName();
	        w = (Workable) PersistenceHelper.manager.refresh(w);
	        if (WorkInProgressHelper.isCheckedOut(w))
	            w = WorkInProgressHelper.service.checkin(w, note);
	        return w;
	    }
	    
}
